import { defineStore } from "pinia";
import * as loginApi from '@/api/login.js'
export const useAccountStore = defineStore("account", {
    actions:{
		login({code='',mobile=''}){
			return new Promise( async (re,rj)=>{
				//校验
				if(!code||!mobile) rj('code or mobile error'); 
				//token user 
				let accessToken,user;  
				// 登陆
				await loginApi.login({
					captchaVerification: code, // 手机验证码
					loginWay: '2', // 1.后台管理 2.微信小程序 3.安卓/IOS/鸿蒙 4.微信公众号  5.三方
					username: mobile, 
					systemMark: 'WMS_MP'
				}).then(res=> ({accessToken:accessToken=''} = res.data||{}));  
				 
				//校验
				if(!accessToken) rj('accessToken is error');
				// 存token
				uni.setStorageSync('Authorization',accessToken); 
				// await this.getAccountInfo().then(res=>({userInfo:user=null}=res)); 
				re('login:true')
			})  
		},
		loginOut(){
			return new Promise((re,rj)=>{
				loginApi.loginOut().then(res=>{
					uni.clearStorageSync();
					this.user = null;
					this.centralWarehouse = null;
					re('loginOut:true')
				}) 
			})
			
		},
        setUser(user){
           this.user = user;
        },
		getUser(){
			return loginApi.getUserInfo()
		},
		getCentralWarehouse(){
			return loginApi.getcentralWarehouse()
		},
		setCentralWarehouse(centralWarehouse){ 
			this.centralWarehouse = centralWarehouse; 
		},
		getAccountInfo(){
			return new Promise(async (re,rj)=>{
				let userInfo,centralWarehouse;
				// 获取用户信息
				await this.getUser().then(res=>({data:userInfo=null}=res));
				//存用户信息
				this.setUser(userInfo);  
				//获取中央仓信息
				await this.getCentralWarehouse().then(res=>({data:centralWarehouse=null}=res));
				//存中央仓信息
				this.setCentralWarehouse(centralWarehouse);
				re({userInfo,centralWarehouse});
			})
			
		}
    },

    state(){
        return {
			 user:null,
			 centralWarehouse:null
		}
    },
});
